package com.mcc.web.controller.common;

import javax.servlet.http.HttpServletResponse;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.mcc.app.carbonEmission.domain.ReportUploadInfo;
import com.mcc.common.exception.CustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.mcc.common.config.ProjectConfig;
import com.mcc.common.constant.Constants;
import com.mcc.common.core.domain.AjaxResult;
import com.mcc.common.utils.StringUtils;
import com.mcc.common.utils.file.FileUploadUtils;
import com.mcc.common.utils.file.FileUtils;
import com.mcc.framework.config.ServerConfig;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author gxy
 */
@Api(tags = "通用")
@ApiSort(2)
@RestController
public class CommonController {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private ServerConfig serverConfig;

    @ApiOperation("通用下载请求")
    @ApiOperationSupport(order = 1)
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }

            String realFileName = fileName.substring(fileName.indexOf("_") + 1);
            String[] array = fileName.split("/");
            String filePath = ProjectConfig.getUploadPath()+"/"+array[array.length-1];//ProjectConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @ApiOperation("通用上传请求")
    @ApiOperationSupport(order = 2)
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = ProjectConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("fileName", fileName);
            data.put("url", url);
            return AjaxResult.success(data);
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }


    @ApiOperation("本地资源通用下载")
    @ApiOperationSupport(order = 3)
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = ProjectConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
